﻿using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm.PlugIn.ControlModel;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using Kingdee.BOS.WebApi.FormService;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kingdee.BOS.ServiceHelper;
using RK.Model.BPW;
using Kingdee.BOS.Log;
using System.Windows.Documents;

namespace RK.FormPlugin.BPW
{
    [Description("打开单据时，自动加载本采购员对应物料的未审核的销售订单"), HotUpdate]
    public class SalConfirmForm : AbstractDynamicFormPlugIn
    {
        //取消关闭时提示是否保存
        public override void BeforeClosed(BeforeClosedEventArgs e)
        {
            base.BeforeClosed(e);
            this.Model.DataChanged = false;
        }
        public override void AfterBarItemClick(AfterBarItemClickEventArgs e)
        {
            base.AfterBarItemClick(e);
            if (e.BarItemKey.EqualsIgnoreCase("XRIS_Refresh"))//刷新
            {
                //删除空行
                var entityRows = this.Model.GetEntryRowCount("FEntity");
                for (int i = entityRows - 1; i >= 0; i--)
                {
                    this.Model.DeleteEntryRow("FEntity", i);
                }
                //获取所有未审核销售订单,按物料编码上对应的采购员与用户的联系对象进行比对筛选
                long userId = this.Context.UserId;
                string purName = GetUserLinkObject(userId);
                var unAuditSalList = GetUnAuditList(purName);
                if (unAuditSalList.Count == 0)
                {
                    return;
                }
                var entity = this.View.BusinessInfo.GetEntity("FEntity");
                //批量创建明细行、填充数据
                this.Model.BatchCreateNewEntryRow("FEntity", unAuditSalList.Count);
                for (int i = 0; i < unAuditSalList.Count; i++)
                {
                    this.Model.SetValue("F_XRIS_SalEntryId", Convert.ToInt32(unAuditSalList[i][0]), i);
                    this.Model.SetValue("F_XRIS_SalCreateDate", Convert.ToDateTime(unAuditSalList[i][1]), i);
                    this.Model.SetValue("F_XRIS_SalNO", Convert.ToString(unAuditSalList[i][2]), i);
                    this.Model.SetValue("F_XRIS_SalStatus", Base.GetStatus(Convert.ToString(unAuditSalList[i][3])), i);
                    this.Model.SetItemValueByNumber("F_XRIS_MaterialId", Convert.ToString(unAuditSalList[i][4]), i);
                    this.Model.SetItemValueByNumber("F_XRIS_SalUnit", Convert.ToString(unAuditSalList[i][5]), i);
                    this.Model.SetValue("F_XRIS_SalQty", Convert.ToDouble(unAuditSalList[i][6]), i);
                    this.Model.SetValue("FDELIVERYDATE", Convert.ToDateTime(unAuditSalList[i][7]), i);
                    this.Model.SetValue("F_BPW_DeliveryDate", Convert.ToDateTime(unAuditSalList[i][8]), i);
                    //带出要货日期和梅州交货日期,然后由用户手工填可交货日期
                    this.Model.SetValue("F_XRIS_OkDate", Convert.ToDateTime(unAuditSalList[i][8]), i);
                    this.Model.SetValue("F_XRIS_AOGDate", Convert.ToDateTime(unAuditSalList[i][7]), i);

                    this.Model.SetValue("FTaxPrice", Convert.ToDecimal(unAuditSalList[i][9]), i);
                    this.Model.SetValue("FPrice", Convert.ToDecimal(unAuditSalList[i][10]), i);
                    this.Model.SetValue("FEntryTaxRate", Convert.ToDecimal(unAuditSalList[i][11]), i);
                    this.Model.SetValue("FEntryTaxAmount", Convert.ToDecimal(unAuditSalList[i][12]), i);
                    this.Model.SetValue("FAmount", Convert.ToDecimal(unAuditSalList[i][13]), i);
                    var tempDate = unAuditSalList[i][14] == null ? "" : "已确认";
                    this.Model.SetValue("F_Notarize", tempDate, i);
                    if (unAuditSalList[i][14] != null)
                    {
                        this.View.StyleManager.SetEnabled("F_XRIS_Select", this.Model.GetEntityDataObject(entity, i), null, true);
                    }
                    this.Model.SetValue("FCustId", Convert.ToString(unAuditSalList[i][15]), i);
                    this.Model.SetValue("F_BPW_SAPNO", Convert.ToString(unAuditSalList[i][16]), i);
                    this.Model.SetValue("F_BPW_SAPORDERNO", Convert.ToString(unAuditSalList[i][17]), i);
                }
            }
            if (e.BarItemKey.EqualsIgnoreCase("XRIS_tbButton"))//确认交期
            {
                List<string> salBillNolist = new List<string>();
                var obj = this.Model.DataObject;
                DynamicObjectCollection rows = obj["FEntity"] as DynamicObjectCollection;
                var newRows = rows.Where(r => Convert.ToInt32(r["F_XRIS_Select"]) == 1);
                if (newRows.Count() <= 0)
                {
                    this.View.ShowErrMessage("未选择任何数据，不允许提交确认！");
                    return;
                }
                foreach (var row in newRows)
                {
                    int salEId = Convert.ToInt32(row["F_XRIS_SalEntryId"]);
                    DateTime temDate = Convert.ToDateTime(row["F_XRIS_OkDate"]);
                    //UptemDate(salEId, temDate);
                    string salBillNo = Convert.ToString(row["F_XRIS_SalNO"]);
                    salBillNolist.Add(salBillNo);
                    Logger.Info("确认交期", this.Context.UserName + $"选择了销售订单{salBillNo}，行内码为:{salEId}的行，并点击了确认交期按钮，确认交期为：{temDate.ToString("d")}");
                }
                //按销售订单号分组，创建出口确认单
                //var distList = salBillNolist.Distinct().ToList();
                //foreach (var dist in distList)
                //{

                //}
                CreateSalConfirmForm("", newRows);
                this.View.ShowMessage("交期确认成功！");
                //Thread.Sleep(TimeSpan.FromSeconds(5));
                //this.View.Close();
            }
        }

        private void UptemDate(int salEId, DateTime temDate)
        {
            string sql = string.Format($@"/*dialect*/ UPDATE T0 SET T0.F_XRIS_TempDate='{temDate}' 
                    FROM T_SAL_ORDERENTRY T0 WHERE T0.FENTRYID = {salEId} ");
            DBServiceHelper.Execute(this.Context, sql);
        }

        /// <summary>
        /// 通过API保存确认单，保存成功，更新销售订单明细行的临时日期字段
        /// </summary>
        /// <param name="dist"></param>
        /// <param name="newRows"></param>
        private void CreateSalConfirmForm(string dist, IEnumerable<DynamicObject> newRows)
        {
            var jsonStr = GetSalConfirmJson(newRows, dist);
            var isOk = CreateSalConfirm(jsonStr);
            if (isOk)
            {
                UpdateSqlEntryTempDate(dist, newRows);
            }
        }
        /// <summary>
        /// 更新销售订单明细行临时日期
        /// </summary>
        /// <param name="dist"></param>
        /// <param name="nRows"></param>
        private void UpdateSqlEntryTempDate(string dist, IEnumerable<DynamicObject> nRows)
        {
            List<string> sqlArray = new List<string>();
            List<List<object>> salEntries = new List<List<object>>();
            //var newRows = nRows.Where(r => Convert.ToString(r["F_XRIS_SalNO"]) == dist && Convert.ToDateTime(r["F_XRIS_OkDate"]) != null && Convert.ToInt32(r["F_XRIS_Select"]) == 1);
            foreach (var row in nRows)
            {
                if (Convert.ToDateTime(row["F_XRIS_OkDate"]) != null && Convert.ToInt32(row["F_XRIS_Select"]) == 1)
                {
                    int eId = Convert.ToInt32(row["F_XRIS_SalEntryId"]);
                    DateTime tempDate = Convert.ToDateTime(row["F_XRIS_OkDate"]);
                    DateTime aogDate = Convert.ToDateTime(row["F_XRIS_AOGDate"]);
                    var salEntrie = new List<object> { eId, tempDate, aogDate };
                    salEntries.Add(salEntrie);
                }
            }
            if (salEntries.Count > 0)
            {
                foreach (var salEntry in salEntries)
                {
                    //,t0.F_BPW_DELIVERYDATE='{Convert.ToDateTime(salEntry[1])}'
                    string sql = string.Format($@"/*dialect*/ UPDATE T0 SET T0.F_XRIS_TempDate='{Convert.ToDateTime(salEntry[1])}' 
                    FROM T_SAL_ORDERENTRY T0 WHERE T0.FENTRYID = {Convert.ToInt32(salEntry[0])} ");
                    sqlArray.Add(sql);
                }
            }
            if (sqlArray.Count > 0)
            {
                DBServiceHelper.ExecuteBatch(this.Context, sqlArray);
            }
        }
        /// <summary>
        /// API保存确认单
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        private bool CreateSalConfirm(string jsonStr)
        {
            bool isSalConfirm = false;
            var creaResult = JsonConvert.SerializeObject(WebApiServiceCall.Save(this.Context, "XRIS_SalConfirmForm", jsonStr));
            JObject result = JObject.Parse(creaResult);
            var isSuccess = result["Result"]["ResponseStatus"]["IsSuccess"].Value<bool>();
            if (isSuccess)
            {
                isSalConfirm = true;
            }
            return isSalConfirm;
        }
        /// <summary>
        /// 构造确认单JSON
        /// </summary>
        /// <param name="nRows"></param>
        /// <param name="dist"></param>
        /// <returns></returns>
        private string GetSalConfirmJson(IEnumerable<DynamicObject> nRows, string dist)
        {
            var date2 = new DateTime(1900, 1, 1);
            var date3 = DateTime.Now;
            string billNo = "JQ" + ((long)new TimeSpan(date3.Ticks - date2.Ticks).TotalSeconds).ToString();
            SalConfirmMedel salCon = new SalConfirmMedel();
            salCon.IsAutoSubmitAndAudit = false;
            salCon.Model = new SalConModel();
            salCon.Model.FBillNo = billNo;
            salCon.Model.FEntity = new List<SalConFEntityItem>();
            //var newRows = nRows.Where(r => Convert.ToString(r["F_XRIS_SalNO"]) == dist && Convert.ToInt32(r["F_XRIS_Select"]) == 1);
            if (nRows.Count() > 0)
            {
                foreach (var row in nRows)
                {
                    SalConFEntityItem enRow = new SalConFEntityItem();
                    enRow.F_XRIS_SalEntryId = Convert.ToInt32(row["F_XRIS_SalEntryId"]);
                    enRow.F_XRIS_SalCreateDate = Convert.ToDateTime(row["F_XRIS_SalCreateDate"]);
                    enRow.F_XRIS_SalNO = Convert.ToString(row["F_XRIS_SalNO"]);
                    enRow.F_XRIS_SalStatus = Convert.ToString(row["F_XRIS_SalStatus"]);
                    DynamicObject material = row["F_XRIS_MaterialId"] as DynamicObject;
                    string mNumber = material["Number"].ToString();
                    enRow.F_XRIS_MaterialId = new GetNumber() { FNumber = mNumber };
                    DynamicObject unit = row["F_XRIS_SalUnit"] as DynamicObject;
                    string uNumber = unit["Number"].ToString();
                    enRow.F_XRIS_SalUnit = new GetNumber() { FNumber = uNumber };
                    enRow.F_XRIS_SalQty = Convert.ToDecimal(row["F_XRIS_SalQty"]);
                    enRow.FDELIVERYDATE = Convert.ToDateTime(row["FDELIVERYDATE"]);
                    var pbwDate = Convert.ToDateTime(row["F_BPW_DeliveryDate"]);
                    if (pbwDate < Convert.ToDateTime("1900-01-01"))
                    {
                        enRow.F_BPW_DeliveryDate = DateTime.Now;
                    }
                    else
                    {
                        enRow.F_BPW_DeliveryDate = pbwDate;
                    }
                    enRow.F_XRIS_OkDate = Convert.ToDateTime(row["F_XRIS_OkDate"]);
                    enRow.F_XRIS_AOGDate = Convert.ToDateTime(row["F_XRIS_AOGDate"]);
                    enRow.FTaxPrice = Convert.ToDecimal(row["FTaxPrice"]);
                    enRow.FPrice = Convert.ToDecimal(row["FPrice"]);
                    enRow.FEntryTaxRate = Convert.ToDecimal(row["FEntryTaxRate"]);
                    enRow.FEntryTaxAmount = Convert.ToDecimal(row["FEntryTaxAmount"]);
                    enRow.FAmount = Convert.ToDecimal(row["FAmount"]);
                    enRow.F_XRIS_Select = Convert.ToInt32(row["F_XRIS_Select"]);
                    enRow.F_XRIS_Remark = row["F_XRIS_Remark"] == null ? "" : row["F_XRIS_Remark"].ToString();
                    enRow.FCustId = row["FCustId"] == null ? "" : row["FCustId"].ToString();
                    enRow.F_BPW_SAPNO = row["F_BPW_SAPNO"] == null ? "" : row["F_BPW_SAPNO"].ToString();
                    enRow.F_BPW_SAPORDERNO = row["F_BPW_SAPORDERNO"] == null ? "" : row["F_BPW_SAPORDERNO"].ToString();
                    salCon.Model.FEntity.Add(enRow);
                }
            }
            return JsonConvert.SerializeObject(salCon);
        }
        /// <summary>
        /// 值更新事件，条件符合设置前景色为红色
        /// </summary>
        /// <param name="e"></param>
        public override void DataChanged(DataChangedEventArgs e)
        {
            base.DataChanged(e);
            var foreColor = "#ff0000";// 红色
            var grid = this.View.GetControl<EntryGrid>("FEntity");
            var yhDate = Convert.ToDateTime(this.Model.GetValue("FDELIVERYDATE", e.Row)).ToString("yyyy-MM-dd");
            DateTime okDate = Convert.ToDateTime(this.Model.GetValue("F_XRIS_OkDate", e.Row));
            //
            DateTime aogDate = okDate.AddDays(60);
            var newDate = aogDate.ToString("yyyy-MM-dd");
            if (e.Field.Key == "F_XRIS_OkDate")
            {
                this.Model.SetValue("F_XRIS_AOGDate", aogDate, e.Row);
                if (yhDate != newDate)
                {
                    grid.SetForecolor("F_XRIS_AOGDate", foreColor, e.Row);
                }
            }
        }
        /// <summary>
        /// 单据加载时，自动加载符合条件的出口订单（销售订单）
        /// </summary>
        /// <param name="e"></param>
        public override void AfterCreateModelData(EventArgs e)
        {
            base.AfterCreateModelData(e);
            //删除空行
            var entityRows = this.Model.GetEntryRowCount("FEntity");
            for (int i = 0; i < entityRows; i++)
            {
                this.Model.DeleteEntryRow("FEntity", i);
            }
            //获取所有未审核销售订单,按物料编码上对应的采购员与用户的联系对象进行比对筛选
            long userId = this.Context.UserId;
            string purName = GetUserLinkObject(userId);
            var unAuditSalList = GetUnAuditList(purName);
            if (unAuditSalList.Count == 0)
            {
                return;
            }
            var entity = this.View.BusinessInfo.GetEntity("FEntity");
            //批量创建明细行、填充数据
            this.Model.BatchCreateNewEntryRow("FEntity", unAuditSalList.Count);
            for (int i = 0; i < unAuditSalList.Count; i++)
            {
                this.Model.SetValue("F_XRIS_SalEntryId", Convert.ToInt32(unAuditSalList[i][0]), i);
                this.Model.SetValue("F_XRIS_SalCreateDate", Convert.ToDateTime(unAuditSalList[i][1]), i);
                this.Model.SetValue("F_XRIS_SalNO", Convert.ToString(unAuditSalList[i][2]), i);
                this.Model.SetValue("F_XRIS_SalStatus", Base.GetStatus(Convert.ToString(unAuditSalList[i][3])), i);
                this.Model.SetItemValueByNumber("F_XRIS_MaterialId", Convert.ToString(unAuditSalList[i][4]), i);
                this.Model.SetItemValueByNumber("F_XRIS_SalUnit", Convert.ToString(unAuditSalList[i][5]), i);
                this.Model.SetValue("F_XRIS_SalQty", Convert.ToDouble(unAuditSalList[i][6]), i);
                this.Model.SetValue("FDELIVERYDATE", Convert.ToDateTime(unAuditSalList[i][7]), i);
                this.Model.SetValue("F_BPW_DeliveryDate", Convert.ToDateTime(unAuditSalList[i][8]), i);
                //带出要货日期和梅州交货日期,然后由用户手工填可交货日期
                this.Model.SetValue("F_XRIS_OkDate", Convert.ToDateTime(unAuditSalList[i][8]), i);
                this.Model.SetValue("F_XRIS_AOGDate", Convert.ToDateTime(unAuditSalList[i][7]), i);

                this.Model.SetValue("FTaxPrice", Convert.ToDecimal(unAuditSalList[i][9]), i);
                this.Model.SetValue("FPrice", Convert.ToDecimal(unAuditSalList[i][10]), i);
                this.Model.SetValue("FEntryTaxRate", Convert.ToDecimal(unAuditSalList[i][11]), i);
                this.Model.SetValue("FEntryTaxAmount", Convert.ToDecimal(unAuditSalList[i][12]), i);
                this.Model.SetValue("FAmount", Convert.ToDecimal(unAuditSalList[i][13]), i);
                var tempDate = unAuditSalList[i][14] == null ? "" : "已确认";
                this.Model.SetValue("F_Notarize", tempDate, i);
                if (unAuditSalList[i][14] != null)
                {
                    this.View.StyleManager.SetEnabled("F_XRIS_Select", this.Model.GetEntityDataObject(entity, i), null, true);
                }
                this.Model.SetValue("FCustId", Convert.ToString(unAuditSalList[i][15]), i);
                this.Model.SetValue("F_BPW_SAPNO", Convert.ToString(unAuditSalList[i][16]), i);
                this.Model.SetValue("F_BPW_SAPORDERNO", Convert.ToString(unAuditSalList[i][17]), i);
            }
        }
        /// <summary>
        /// 获取出口订单
        /// </summary>
        /// <param name="purName"></param>
        /// <returns></returns>
        private List<List<object>> GetUnAuditList(string purName)
        {
            string formId = "SAL_SaleOrder";
            string fieldKeys = "FSaleOrderEntry_fentryid,fdate,fbillno,FDocumentStatus,fmaterialid.fnumber,FUnitID.fnumber,FQty,FPlanDate,F_BPW_DeliveryDate,FTaxPrice,FPrice,FEntryTaxRate,FEntryTaxAmount,FAmount,F_XRIS_TempDate,FCustId.FNAME,F_BPW_SAPNO,F_BPW_SAPORDERNO";
            string filterString = $"FDocumentStatus='A' and fmaterialid.FPurchaserId='{purName}' AND F_XRIS_TempDate IS NULL AND FBillTypeID.FNUMBER='XSDD02_BPW'";
            var result = WebApiServiceCall.ExecuteBillQuery(this.Context, Base.QueryParameter(formId, fieldKeys, filterString));
            return result;
        }
        /// <summary>
        /// 获取采购员
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        private string GetUserLinkObject(long userId)
        {
            string purName = "";
            var result = WebApiServiceCall.ExecuteBillQuery(this.Context, Base.QueryParameter("SEC_User", "FLinkObject.fname", $"fuserid={userId}"));
            if (result.FirstOrDefault().FirstOrDefault() != null)
            {
                purName = result.FirstOrDefault().FirstOrDefault().ToString();
            }
            return purName;
        }
    }
}
